package client;

import java.util.*; 
import java.sql.*; 
import java.io.*; 

/** 
* This file contains the code for the SerializedRS. 
* It acts as a wrapper class for the JDBC Result Set class.
* Creation date: 20/05/2014
* @author: Tomer Elkayam 
*/ 

public class SerializedRS
{
	private ArrayList<HashMap<String,String>> rowSet;	// Rowset for storing the ResultSet Data 
	private int rowCount; 								// Number of rows retreived from the Database 
	private String BLANKSPACE;	 						// Used to fill the null fields in database 

	/** 
	* SerializedRS constructor. 
	*/ 
	public SerializedRS()
	{
		rowSet = new ArrayList<HashMap<String,String>>();
		rowCount = 0; 
		BLANKSPACE = "";
	}
	
	public SerializedRS(ResultSet rs) throws SQLException 
	{ 
		this();
		populateRecords(rs); 
	}

	/** 
	* This method is used to return the number of records in the HASTABLE( Number of rows retreived from database). 
	*/ 
	public int getRowCount() 
	{ 
		return rowCount; 
	} 
	
	/** 
	* Return the set - a List of hash maps , each hash map is a row
	*  
	*/ 
	public ArrayList<HashMap<String,String>> getRowSet() 
	{ 
		return rowSet; 
	} 
	
	/** 
	* This method gets the records from the regular RS and puts them to the new serialized RS 
	* @param rs ResultSet 
	*/ 
	private void populateRecords(ResultSet rs) throws SQLException 
	{ 
		ResultSetMetaData rsmdResult = null; 
		int columns = 0; 
		String strColname = null; 
		String strColvalue = null; 
		
		HashMap <String,String> oneRow;
	
		rsmdResult = rs.getMetaData(); 
		columns = rsmdResult.getColumnCount(); 
	
		do
		{ 
			rowCount++;
			oneRow = new HashMap<String,String>(); 
			
			for(int i = 1; i <= columns;i++) 
			{ 
				strColname = rsmdResult.getColumnName(i); 
				strColvalue = rs.getString(strColname); 
				if(rs.wasNull()) 
					strColvalue=BLANKSPACE; 
				
				oneRow.put(strColname.toUpperCase(),strColvalue); 
				//NOTE: THE COLUMN NAMES WILL ALWAYS BE STORED IN UPPERCASE, 
				//HENCE NEED TO BE RETRIEVED IN UPPER CASE 
			} 
			rowSet.add(oneRow); 
		} 
		while(rs.next());
	} 
	 
}// end of class 

